import axios,{ type InternalAxiosRequestConfig,type AxiosError,type AxiosRequestConfig } from "axios";

interface AxiosRequestConfigEx extends AxiosRequestConfig{
  donNotShowLoading?:boolean
}
export type ResType<T = unknown>={
  code:string
  data:T
  msg:string
}
export type pageDataType<T>={
  list:T[]
  pageNum:number
  pageSize:number
  total:number
}
export type RolesType={
  code:string
  createTime?:string
  id?:number
  name:string
  sort:number
  status:number
}
const instance=axios.create({
  baseURL:'http://localhost:8989',
  timeout:2000,
})
instance.interceptors.request.use((config:InternalAxiosRequestConfig)=>{
  config.headers.set('Content-Type','application/json')
  if(config.method == 'post'){
    config.data=JSON.stringify(config.data)
  }
  return config
},
(error:AxiosError)=>{
  Promise.reject(error)
})
instance.interceptors.response.use(
  (response)=>{
    return response.status == 200 ? Promise.resolve(response) : Promise.reject(response)
},
(error)=>{
  const {response}=error
  errorHanld(response.status,response.info)
}
)
const errorHanld=(status:number,info:string)=>{
  switch (status) {
    case 400:
    console.log('语义有误');
      break;
    case 401:
    console.log('服务器认证');
    window.location.href='/LoginView'
      break;
    case 402:
    console.log('服务器拒绝访问');
      break;
    case 403:
    console.log('地址有误');
      break;
    case 500:
    console.log('服务器遇到意外');
    break;
    case 502:
    console.log('服务器无响应');
    break;
    default:
      console.log(info);
      break;
  }
}
export const service = <T = unknown>(config: AxiosRequestConfigEx): Promise<ResType<T>>=>{
  return instance
  .request<ResType<T>>(config)
  .then((response)=>{
    return response.data
  })
  .catch((error)=>{
    console.error(error);
    throw error
  })
}
interface GetRolesPagewParams{
  pageNum:number
  pageSize:number
}
export const requestGetRolesPage=(params:GetRolesPagewParams)=>{
  return service<pageDataType<RolesType>>({
    method:'GET',
    url:'/roles/page',
    params,
  })
  // return instance
  // .request<ResType<pageDataType<RolesType>>>({
  //   method:'GET',
  //   url:'/roles/page',
  //   params,
  // }).then((response)=>{
  //   return response.data
  // }).catch((error)=>{
  //   console.error(error)
  // })
}

export const addRole=(data:RolesType)=>{
  return service({
    method:'POST',
    url:'/roles',
    data
  })
}
export const editRole=(roleId:string,data:Partial<RolesType>)=>{
  service({
    method:'PUT',
    url:`/roles/${roleId}`,
    data
  })
}
export const editRolesStatus=(roleId:string,status:number)=>{
  return service({
    method:'PATCH',
    url:`/roles/${roleId}/status`,
    params:{status}
  })
}
export const deRole=(id:string)=>{
  return service({
    method:'DELETE',
    url:`/roles/${id}`,
  })
}
